<?php

namespace App\Console\Commands;

use App\Admin\Models\SiteCompany;
use App\Store\Models\Member\Member;
use App\Store\Models\Message\Rule;
use App\Store\Services\Message\Lianlu;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

/**
 * 节日回访
 */
class GetFestivalMember extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:GetFestivalMemberList';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '获取节日用户列表';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        Log::info('获取节日用户列表开始');
        $this->getrulelist();
        Log::info('获取节日用户列表结束');
        return 0;
    }

    public function getrulelist()
    {
        $y_m_d = date('Y-m-d');
        $list = Rule::where(['type' => 5, 'status' => 2, 'is_del' => 1, 'date' => $y_m_d])->get();
        if ($list) {
            $list = $list->toArray();
            foreach ($list as $rule) {
                $this->getFestival($rule);
            }
        } else {
            Log::info('没有配置节日规则');
        }
    }

    public function getFestival($rule)
    {
        $list = Member::where([
            'cp_id' => $rule['cp_id'],
            'store_id' => $rule['store_id'],
            'is_del' => 1,
        ])->get();
        if (!$list) {
            Log::info('店铺没有人');
            return 0;
        }
        $list = $list->toArray();

        $phone_arr = [];
        foreach ($list as $item) {
            if (!empty($item['mobile'])) {
                $phone_arr[] = $item['mobile'];
            }
        }

        if ($phone_arr) {
            $companyinfo = SiteCompany::where([['id',$rule['cp_id']],['is_open_sms',2]])->first();
            if(!$companyinfo){
                return response()->json(['code' => '001', 'msg' => '短信未开启']);
            }
            Log::info('手机号：'.json_encode($phone_arr));
            Log::info('短信内容：'.$rule['content']);
            Log::info('公司信息：'.json_encode($companyinfo));
            $this->sendMessage($phone_arr, $rule['content'], $companyinfo);
            return true;
        } else {
            Log::info('公司ID：'.$rule['cp_id'].'，门店ID：'.$rule['store_id'].'，用户手机号为空');
            return 0;
        }
    }

    public function sendMessage($phone_arr, $content, $companyinfo)
    {
        $res=Lianlu::NormalSend($phone_arr, $content, $companyinfo);
        info('节日回访短信发送结果' . $res);
        return true;
    }
}
